package com.app.jwt.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

public class JWTUtils {

    private static final String SIGN = "token!hnds20211227";

    /**
     * 生成token
     *
     * @param map
     * @return
     */
    public static String getToken(Map<String, Object> map) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND, 60 * 30);   // 默认30分钟过期
        // 生成令牌
        JWTCreator.Builder builder = JWT.create();
        map.forEach((k, v) -> {
            builder.withClaim(k, (String) v);
        });
        String token = builder.withExpiresAt(instance.getTime()) // 设置过期时间
                .sign(Algorithm.HMAC256(SIGN));   // 设置签名
        return token;
    }


    /**
     * 验证token
     *
     * @param token
     */
    public static void verify(String token) {
        JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
    }

    /**
     * 获取token信息
     *
     * @param token
     * @return
     */
    public static DecodedJWT getTokenInfo(String token) {
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
        return decodedJWT;
    }

}